package net.hotelOrderSystem.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradeCancelRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import net.hotelOrderSystem.domain.*;
import net.hotelOrderSystem.service.HotelService;
import net.hotelOrderSystem.service.OrderService;
import net.hotelOrderSystem.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import net.hotelOrderSystem.service.UserService;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/HTML/*")
public class UserController {
    protected  static    String curAccount;
    protected static String reRoomStatus="000000000000000000000000000000000000000000000000000000000000";
    private   String curHotelId;
    private   String curRoomNumber;
    private  String  curOrderId;
    private  int curdistance;
    private  List<Hotel> curHotels;
    private  List<String> starList=Arrays.asList("0","1","2","3","4");
    public String getCurAccount() {
        return curAccount;
    }
    //输入字符串B，用字符串A做模板，输出Date类型的A
    public Date stringToDate(String stringB) throws ParseException {
        SimpleDateFormat stringA=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
        Date dateA=stringA.parse(stringB);
        return dateA;
    }
    @Autowired
    private UserService userService;
    @Autowired
    private HotelService hotelService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private OrderService orderService;

    @GetMapping("/login")
    public  String showIndex(Model model)
    {
        model.addAttribute("flag",2);
        return "HTML/login";
    }
    //注销
    @GetMapping("/relogin")
    public  String relogin(Model model)
    {
        model.addAttribute("flag",2);
        curAccount=null;
        reRoomStatus=null;
        curHotelId=null;
        curRoomNumber=null;
        curOrderId=null;
        curdistance=0;
        curHotels=null;
        return "HTML/login";
    }
    @GetMapping("/register")
    public  String showRegister(Model model)
    {
        model.addAttribute("flag",2);
        return "HTML/register";
    }
    @GetMapping("/home")
    public  String showHome(Model model)
    {
        model.addAttribute("account", curAccount);
        return "HTML/home";
    }
    @GetMapping("/adminHome")
    public  String showAdminHome(Model model)
    {
        model.addAttribute("account", curAccount);
        return "HTML/adminHome";
    }
    //主页去到条件搜索
    @GetMapping("/conditionSearch")
    public String conditionSearch(Model model)
    {
        return "HTML/conditionSearch";
    }
    @PostMapping("/locationSearch")
    public String showMap(){
        return "HTML/location";
    }
    @PostMapping("/userInfoUpdate")
    public  String userInfoUpdate(Model model)
    {
        User user = userService.findUserByAccount(curAccount);
        model.addAttribute("user",user);
        return "HTML/userInfo";
    }
    @PostMapping("/updatePassword")
    public  String userPasswordUpdate(Model model){
        model.addAttribute("flag",0);
        return "HTML/updatePassword";
    }
    //登录
    @PostMapping("/index")
    public String login(Model model,@RequestParam("account")String account,
                        @RequestParam("password")String password,Model model1){
        int flag;
        if(userService.findUserByAccount(account)==null){
            flag=1;
            model.addAttribute("flag",flag);
            return "/HTML/login";
        }
        else if(userService.findUserByAccount(account).getPassword().equals(password)) {
            String name=userService.findUserByAccount(account).getName();
            model.addAttribute("account", account);
            model.addAttribute("name", name);
            curAccount =account;
            flag=0;
            model.addAttribute("flag",flag);
            if(userService.findUserByAccount(account).getRole().equals("管理员")||
                    userService.findUserByAccount(account).getRole().equals("超级管理员"))
                return "HTML/adminHome";//进入管理员主页
            else
                return "HTML/home";//进入用户主页
        }
        else {
            flag=1;
            model.addAttribute("flag",flag);
            return "/HTML/login";
        }
    }

    //注册
    @PostMapping("/registerIn")
    public String register(Model model,@RequestParam("account")String account,@RequestParam("password")String password ){
        int flag =0;
        if(userService.findUserByAccount(account)==null) {
            User user = new User(account, null, "", "", "", "", password, "", "");
            userService.saveUser(user);
            return "HTML/login";
        }
        else {
            flag = 1;
            model.addAttribute("flag",flag);
            return  "/HTML/register";
        }
    }


    //用户查看信息
    @PostMapping("/userInfo")
    public String showUserInformation(Model model) {
        User user = userService.findUserByAccount(curAccount);
        model.addAttribute("user", user);
        return "/HTML/userInfo";
    }

    //用户修改信息
    @PostMapping("/userInfoUpdateTo")
    public String changInfomationByUser(
            @RequestParam("user.age")Short age,
            @RequestParam("user.name")String name,
            @RequestParam("user.phone")String phone,
            @RequestParam("user.mail")String mail,
            @RequestParam("user.gender")String gender,
//          @RequestParam("user.role")String role,
//          @RequestParam("user.premission")String premission,
            Model model){
        System.out.println(userService.findUserByAccount(curAccount).getName());
        int isUpdate=0;
        String role =userService.findUserByAccount(curAccount).getRole();
        String premission=userService.findUserByAccount(curAccount).getPremission();
        if(age==null)age=userService.findUserByAccount(curAccount).getAge();
        if (name=="")name=userService.findUserByAccount(curAccount).getName();
        System.out.println(name);
        if (phone=="")phone=userService.findUserByAccount(curAccount).getPhone();
        if (mail=="")mail=userService.findUserByAccount(curAccount).getMail();
        if (gender=="")gender=userService.findUserByAccount(curAccount).getGender();
        User user =new User(curAccount,age,name,phone,mail,gender,userService.findUserByAccount(curAccount).getPassword(),role,premission);
        userService.updateUserByAccount(curAccount,user);
        User user1 = userService.findUserByAccount(curAccount);
        model.addAttribute("user", user1);
        model.addAttribute("isUpdate",isUpdate);
        return "/HTML/userInfo";
    }

    //用户修改密码
    @PostMapping("/updatePasswordTo")
    public String changPassword(@RequestParam("password")String password,@RequestParam("newPassword")String newPassword,Model model,Model model1){
        User user = userService.findUserByAccount(curAccount);
        int flag;
        if (user.getPassword().equals(password)) {
            user.setPassword(newPassword);
            userService.updateUserByAccount(curAccount, user);
            flag=0;
            model.addAttribute("account",curAccount);
            model1.addAttribute("flag",flag);
            return "/HTML/home";
        }
        else
        {
            flag=1;
            model1.addAttribute("flag",flag);
            return "/HTML/updatePassword";
        }
    }

    //条件搜索
    @PostMapping("/conditionSearch")
    public String conditionSearch() {
        return "/HTML/conditionSearch";
    }
    //查看酒店详细信息
    @PostMapping("/reHotelInfo")
    public String reHotelInfo(@RequestParam("hotelId")String hotelId ,Model model){
        Hotel hotel= hotelService.findHotelByID(hotelId);
        curHotelId =hotelId;
        model.addAttribute("hotel",hotel);
        return "/HTML/hotelHome";
    }
    //根据经纬度 查看酒店信息
    @PostMapping("/reHotelInfoBylocation")
    public String reHotelInfo(@RequestParam("a")String longitude ,@RequestParam("b")String latitude, Model model){
        System.out.println(longitude+" "+latitude);
        Hotel hotel=hotelService.findHotelByLocation(longitude,latitude);
        curHotelId =hotel.getHotelId();
        model.addAttribute("hotel",hotel);
        return "/HTML/hotelHome";
    }
    //创建订单页面
    @PostMapping("createOrder")
    public  String createOrder(Model model){
        model.addAttribute("account", curAccount);
        Hotel hotel = hotelService.findHotelByID(curHotelId);
        model.addAttribute("hotel",hotel);
        List<Room> rooms = roomService.findRoomByHotelId(curHotelId);
        Date now = new Date();
        int updateNum=0;
        model.addAttribute("rooms",rooms);
        System.out.println(rooms.size());
        String orderId;
        Date date = new Date();
        int  num =  (int)(Math.random()*100);
        orderId = ""+date.getTime()+num+curAccount;
        model.addAttribute("orderId",orderId);
        return "/HTML/inputOrderInfo";
    }
    //从酒店列表直接创建订单
    @PostMapping("createOrderFromList")
    public  String createOrderFromList(@RequestParam("hotelId")String hotelId ,Model model){
        curHotelId=hotelId;
        model.addAttribute("account", curAccount);
        Hotel hotel = hotelService.findHotelByID(hotelId);
        model.addAttribute("hotel",hotel);
        List<Room> rooms = roomService.findRoomByHotelId(hotelId);
        Date now = new Date();
        int updateNum=0;
        model.addAttribute("rooms",rooms);
        System.out.println(rooms.size());
        String orderId;
        Date date = new Date();
        int  num =  (int)(Math.random()*100);
        orderId = ""+date.getTime()+num+curAccount;
        model.addAttribute("orderId",orderId);
        return "/HTML/inputOrderInfo";
    }
    //主页查订单列表
    @PostMapping("lookOrderList")
    public String lookOrderList(Model model){
        List<Order> orders =orderService.findOrderByAccount(curAccount);
        List<Hotel> hotels =hotelService.findHotel();
        hotels.clear();
        Hotel hotel;
        for (int i=0;i<orders.size();i++)
        {
            hotel=hotelService.findHotelByID(roomService.findRoomByRoomNumber(orders.get(i).getRoomNumber()).getHotelId());
            hotels.add(hotel);
        }
        model.addAttribute("hotels",hotels);
        model.addAttribute("orders",orders);
        return "/HTML/orderList";
    }

    //用户创建订单
    @PostMapping("createOrderTo")
    public String createOrderTo(@RequestParam("orderId")String orderId ,
                               @RequestParam("inNumber")Short inNumber,  @RequestParam("inTime")String inTime,
                               @RequestParam("outTime")String outTime, @RequestParam("roomNumber")String roomNumber,
                               Model model) throws ParseException {
        String[] roomNumbers=roomNumber.split(",");
      for(int i=0;i<roomNumbers.length;i++){
          if(roomNumbers[i]!="0"){
              roomNumber=roomNumbers[i];
              break;
          }
      }
      String roomType=roomService.findRoomByRoomNumber(roomNumber).getRoomType();
//        SimpleDateFormat inString=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
//        Date inDate=inString.parse(inTime);
//        SimpleDateFormat outString=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
//        Date outDate=outString.parse(outTime);
        Date inDate=stringToDate(inTime);
        Date outDate=stringToDate(outTime);
        System.out.println(outDate.getTime()+"wdq"+inDate.getTime());
        int daynum=(int) (outDate.getTime()-inDate.getTime())/(1000*60*60*24);
        String hotelName = hotelService.findHotelByID(curHotelId).getHotelName();
        System.out.println(roomNumber);
        int price = roomService.findRoomByRoomNumber(roomNumber).getPrice();
        price=price*(daynum+1);
        System.out.println(price);
        Integer orderStatus = 0;
        Integer paymentStatus = 0;
        Order order = new  Order(orderId,  curAccount,  hotelName,  roomType,  inNumber,  inDate,  outDate,  orderStatus,  paymentStatus,  roomNumber,price);
        Room room =roomService.findRoomByRoomNumber(roomNumber);
        //更改房间的入住状态
        Date now = new Date();
        int beginNum = (int) ((inDate.getTime()-now.getTime())/(1000*60*60*24));
        int  endNum = (int) ((outDate.getTime()-now.getTime())/(1000*60*60*24));
        System.out.println(beginNum+"\n"+endNum);
        StringBuilder states=null;
//        states.append(room.getRoomStatus());
//        states.replace(beginNum,endNum,"1");
//        room.setRoomStatus(states.toString());
//        roomService.updateRoomByRoomNumber(roomNumber,room);
        //返回订单列表
        orderService.saveOrder(order);

        List<Order> orders =orderService.findOrderByAccount(curAccount);
        List<Hotel> hotels =hotelService.findHotel();
        hotels.clear();
        Hotel hotel;
        for (int i=0;i<orders.size();i++)
        {
            hotel=hotelService.findHotelByID(roomService.findRoomByRoomNumber(orders.get(i).getRoomNumber()).getHotelId());
            hotels.add(hotel);
        }
        model.addAttribute("hotels",hotels);
        model.addAttribute("orders",orders);
        return  "/HTML/orderList";
    }

    //用户条件搜索
    @PostMapping ("/searchByConditionTo")
    public  String searchByCondition(@RequestParam("city") String city,@RequestParam("inDate") String inTime,
                                     @RequestParam("outDate") String outTime,@RequestParam("inNumber") String inNumber,
                                     Model model) throws ParseException {
        Date inDate=stringToDate(inTime);
        Date outDate=stringToDate(outTime);

//        System.out.println(inDate+"\n"+outDate);
        HotelExample hotelExample = new HotelExample();
        hotelExample.createCriteria().andCityEqualTo(city);
        List<Hotel> hotels =hotelService.findHotel();
        curHotels =hotels;
        model.addAttribute("hotels",hotels);
        model.addAttribute("slist",starList);
        return "/HTML/searchResultByList";
    }
    //查看订单
    @PostMapping("/orderHome")
    public String showOrderHome(@RequestParam("orderId") String orderId, Model model){
        Order order = orderService.findOrderByID(orderId);
        curOrderId=orderId;
        model.addAttribute("hotel",hotelService.findHotelByID(roomService.findRoomByRoomNumber
                (orderService.findOrderByID(orderId).getRoomNumber()).getHotelId()));
        model.addAttribute("order",order);
        return  "/HTML/orderHome";
    }
    //修改订单详情
    @PostMapping("updateOrderInfo")
    public String updateOredrInfo(@RequestParam("roomType")String roomType,
                                  @RequestParam("inNumber")Short inNumber,  @RequestParam("inTime")String inTime,
                                  @RequestParam("outTime")String outTime, @RequestParam("roomNumber")String roomNumber,Model model) throws ParseException {
        String hotelName = orderService.findOrderByID(curOrderId).getHotelName();
        roomNumber=orderService.findOrderByID(curOrderId).getRoomNumber();
        int price = roomService.findRoomByRoomNumber(roomNumber).getPrice();
        Integer orderStatus = orderService.findOrderByID(curOrderId).getOrderStatus();
        Integer paymentStatus = orderService.findOrderByID(curOrderId).getPaymentStatus();

        if(inTime=="")inTime=orderService.findOrderByID(curOrderId).getInTime().toString();
        if(outTime=="")inTime=orderService.findOrderByID(curOrderId).getOutTime().toString();

        SimpleDateFormat inString=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
        Date inDate=inString.parse(inTime);
        SimpleDateFormat outString=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
        Date outDate=outString.parse(outTime);

        if(roomType=="")roomType=orderService.findOrderByID(curOrderId).getRoomType();
        if(inNumber==null)inNumber=orderService.findOrderByID(curOrderId).getInNumber();

        Order order = new  Order(curOrderId,  orderService.findOrderByID(curOrderId).getAccount(),  hotelName,  roomType,  inNumber,  inDate,  outDate,  orderStatus,  paymentStatus,  roomNumber,price);
        orderService.updateOrderByID(curOrderId,order);
        model.addAttribute("order",orderService.findOrderByID(curOrderId));
        model.addAttribute("hotel",hotelService.findHotelByID(roomService.findRoomByRoomNumber
                (orderService.findOrderByID(curOrderId).getRoomNumber()).getHotelId()));
        return "/HTML/orderHome";
    }
    /*
      * 根据经纬度计算两点之间的距离（单位km）
      * */
    public static String algorithm(double longitude1, double latitude1, double longitude2, double latitude2) {

        double Lat1 = rad(latitude1); // 纬度

        double Lat2 = rad(latitude2);

        double a = Lat1 - Lat2;//两点纬度之差

        double b = rad(longitude1) - rad(longitude2); //经度之差

        double s = 2 * Math.asin(Math

                .sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(b / 2), 2)));//计算两点距离的公式

        s = s * 6378137.0;//弧长乘地球半径（半径为米）

        s = Math.round(s * 10000d) / 10000d;//精确距离的数值
        s = s/1000;//将单位转换为km，如果想得到以米为单位的数据 就不用除以1000
        //四舍五入
        DecimalFormat df = new DecimalFormat("#");

        return df.format(s);

    }
    private static double rad(double d) {
        return d * Math.PI / 180.00; //角度转换成弧度
    }
    //用户关键词搜索酒店
    @PostMapping("/searchByKeyword")
    public String searchByKeyword(@RequestParam("keyword")String keyword ,Model model){
        int searchflag =0;
        List<Hotel> hotels=hotelService.findHotelByKeyword(keyword);
        curHotels =hotels;
        model.addAttribute("hotels",hotels);
        if (hotels.size()>0) {
            model.addAttribute("slist",starList);
            return "/HTML/searchResultByList";
        }
        else {
            searchflag = 1;
            model.addAttribute("account",curAccount);
            model.addAttribute("flag",searchflag);
            return "/HTML/home";
        }
    }
    //景点地标搜索
    @PostMapping("searchByLandmark")
    public String searchBylandmark(Model model,@RequestParam("keyword")String landmark){
        model.addAttribute("landmark",landmark);
        return "/HTML/searchByLandmark";
    }
    //景点地标搜索附近酒店结果传回
    @PostMapping("searchResultByLandmark")
    public String searchResultByLandmark(Model model,@RequestParam("a")String longitude,
                                         @RequestParam("b")String latitude)
    {
        List<Hotel> hotels =hotelService.findHotel();
        List<Hotel> hotels2 = hotelService.findHotel();
        hotels2.clear();
        double longitude1,latitude1,longitude2,latitude2;
        latitude1=Double.parseDouble(latitude);
        longitude1=Double.parseDouble(longitude);
        for(int i=0;i<hotels.size();i++)
        {
            longitude2= Double.parseDouble(hotels.get(i).getLongitude());
            latitude2=Double.parseDouble((hotels.get(i).getLatitude()));
            if((Integer.parseInt(algorithm(longitude1,latitude1,longitude2,latitude2)))<2){
                hotels2.add(hotels.get(i));
            }
        }
        curHotels = hotels2;
        model.addAttribute("hotels",hotels2);
        model.addAttribute("jingdu",longitude);
        model.addAttribute("weidu",latitude);
        System.out.println(longitude+"||"+latitude);
        model.addAttribute("radius",2);
        return "/HTML/searchResultByMap";
    }


    //用户筛选搜索
    @PostMapping("/searchByFilterTo")
    public  String searchByFilter(@RequestParam("city") String city,
                                  @RequestParam("priceLow") Integer priceLow, @RequestParam("priceTop") Integer priceTop,
                                  @RequestParam("star") double  star, @RequestParam("rate") double rate,
                                  @RequestParam("brand")String brand,
                                  Model model){
        List<Hotel> hotels =hotelService.findHotelByFilter(city,priceLow,priceTop,star,rate,brand);
        curHotels = hotels;
        model.addAttribute("hotels",hotels);
        model.addAttribute("slist",starList);
        return "/HTML/searchResultByList";
    }
    //附近搜索确定当前位置
    @PostMapping("/searchByMap")
    public String searchByMap(@RequestParam("keyword") Integer distance){
        curdistance=distance;
        return "/HTML/searchCurLocation";
    }
    //附近搜索
    @PostMapping("/searchByDistance")
    public String searchByDistance(@RequestParam("longitude")String longitude,@RequestParam("latitude")String latitude, Model model){
        List<Hotel> hotels =hotelService.findHotel();
        List<Hotel> hotels2 = hotelService.findHotel();
        hotels2.clear();
        double longitude1,latitude1,longitude2,latitude2;
        latitude1=Double.parseDouble(latitude);
        longitude1=Double.parseDouble(longitude);
        for(int i=0;i<hotels.size();i++)
        {
            longitude2= Double.parseDouble(hotels.get(i).getLongitude());
            latitude2=Double.parseDouble((hotels.get(i).getLatitude()));
            if((Integer.parseInt(algorithm(longitude1,latitude1,longitude2,latitude2)))<curdistance){
                hotels2.add(hotels.get(i));
            }
        }
//        System.out.println(hotels2.size());
//        for (int i=0;i<hotels2.size();i++){
//            System.out.println(hotels2.get(i).getLongitude()+"!"+i+"!"+hotels2.get(i).getLatitude());
//        }
        curHotels =hotels2;
        model.addAttribute("hotels",hotels2);
        //返回经纬度，longitude是经度
        model.addAttribute("jingdu",longitude);
        model.addAttribute("weidu",latitude);
        //返回半径
        model.addAttribute("radius",curdistance);
        return "/HTML/searchResultByMap";
    }
    //酒店显示方式转换:地图到列表
    @PostMapping("mapToList")
    public String mapToList(Model model){
        model.addAttribute("hotels",curHotels);
        model.addAttribute("slist",starList);
        return "/HTML/searchResultByList";
    }
    //酒店显示方式转换:列表到地图
    @PostMapping("listToMap")
    public String listToMap(Model model){
        model.addAttribute("hotels",curHotels);
        return "/HTML/ListToMap";
    }
    //+++撤销订单
    @PostMapping("drawOrder")
    public String drawOrder(Model model,@RequestParam("orderId") String orderId){
        int flag=1;
        if(orderService.findOrderByID(orderId).getPaymentStatus()==0){
            orderService.deleteOrderByID(curOrderId);
            curOrderId ="";
            flag=0;
        }
        model.addAttribute("orders",orderService.findOrderByAccount(curAccount));
        model.addAttribute("flag",flag);
        return "/HTML/orderList";
    }
    //删除订单
    @PostMapping("deleteOrder")
    public String deleteOrder(Model model,@RequestParam("orderId") String orderId){
        int flag=1;
        if ((orderService.findOrderByID(orderId).getPaymentStatus()==1
                && orderService.findOrderByID(orderId).getOrderStatus()==2)||
                (orderService.findOrderByID(orderId).getPaymentStatus()==0
                && orderService.findOrderByID(orderId).getOrderStatus()==0)){
            orderService.deleteOrderByID(orderId);
            curOrderId="";
            flag=0;//成功
        }
        List<Order> orders =orderService.findOrderByAccount(curAccount);
        List<Hotel> hotels =hotelService.findHotel();
        hotels.clear();
        Hotel hotel;

        for (int i=0;i<orders.size();i++)
        {
            hotel=hotelService.findHotelByID(roomService.findRoomByRoomNumber(orders.get(i).getRoomNumber()).getHotelId());
            hotels.add(hotel);
        }
        model.addAttribute("hotels",hotels);
        model.addAttribute("orders",orders);
        model.addAttribute("flag",flag);
        return "/HTML/orderList";
    }
    //退单退钱
    @PostMapping("refund")
    public String refund(Model model,@RequestParam("orderId") String orderId){
        int flag=1;
        //这里改了，原来是1和1，现在是1和0，应该是支付了但是没开始才能退单
        if (orderService.findOrderByID(orderId).getPaymentStatus()==1
                &&orderService.findOrderByID(orderId).getOrderStatus()==0) {
            flag =0;
            int price;
            int dayNum,dayAll;
            Date now = new Date();
            dayAll = (int)((orderService.findOrderByID(orderId).getOutTime().getTime()-orderService.findOrderByID(orderId).getInTime().getTime())/(1000*60*60*24));
            dayNum = (int)((orderService.findOrderByID(orderId).getOutTime().getTime()-now.getTime())/(1000*60*60*24));
            System.out.println(dayAll+"!!!"+dayNum);
            price = orderService.findOrderByID(orderId).getPrice()/((dayAll+1)/(dayNum+1));
            Order order = orderService.findOrderByID(orderId);
            order.setPaymentStatus(0);
            orderService.saveOrder(order);
            model.addAttribute("price",price);
        }
        model.addAttribute("flag",flag);

        List<Order> orders =orderService.findOrderByAccount(curAccount);
        List<Hotel> hotels =hotelService.findHotel();
        hotels.clear();
        Hotel hotel;

        for (int i=0;i<orders.size();i++)
        {
            hotel=hotelService.findHotelByID(roomService.findRoomByRoomNumber(orders.get(i).getRoomNumber()).getHotelId());
            hotels.add(hotel);
        }
        model.addAttribute("hotels",hotels);
        model.addAttribute("orders",orders);
        return "/HTML/orderList";
    }
    //退款成功
    @GetMapping("refundSuccess")
    public String refundSuccess(Model model){
        Order order = orderService.findOrderByID(curOrderId);
        order.setPaymentStatus(0);
        orderService.saveOrder(order);
        List<Order> orders =orderService.findOrderByAccount(curAccount);
        List<Hotel> hotels =hotelService.findHotel();
        hotels.clear();
        Hotel hotel;
        for (int i=0;i<orders.size();i++)
        {
            hotel=hotelService.findHotelByID(roomService.findRoomByRoomNumber(orders.get(i).getRoomNumber()).getHotelId());
            hotels.add(hotel);
        }
        model.addAttribute("orders",orders);
        model.addAttribute("hotels",hotels);
        return "/HTML/orderList";
    }
    //支付
    @PostMapping("payForOrder")
    public String payForOrder(Model model,@RequestParam("orderId") String orderId) throws WriterException, IOException {
       if(orderService.findOrderByID(orderId).getPaymentStatus().equals(0)){
        int price;
        curOrderId=orderId;
        price = orderService.findOrderByID(orderId).getPrice();
        model.addAttribute("price",price);
        String text = "订单号："+curOrderId+"\n"+"价格："+price+"\n"; // 二维码内容
        int width = 300; // 二维码图片宽度
        int height = 300; // 二维码图片高度
        String format = "jpg";// 二维码的图片格式

        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码

        BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
                BarcodeFormat.QR_CODE, width, height, hints);
        // 生成二维码
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        String base64Img = Base64Utils.encodeToString(outputStream.toByteArray());
        String res = "data:image/jpg;base64," + base64Img.toString();
        model.addAttribute("QRImage",res);
        model.addAttribute("orderId",orderId);
        outputStream.close();

        return "/HTML/pay";}
        else {
           List<Order> orders =orderService.findOrderByAccount(curAccount);
           List<Hotel> hotels =hotelService.findHotel();
           hotels.clear();
           Hotel hotel;
           for (int i=0;i<orders.size();i++)
           {
               hotel=hotelService.findHotelByID(roomService.findRoomByRoomNumber(orders.get(i).getRoomNumber()).getHotelId());
               hotels.add(hotel);
           }
           model.addAttribute("orders",orders);
           model.addAttribute("hotels",hotels);
           return "/HTML/orderList";
       }
    }
    //+++支付成功
    @GetMapping("paySuccess")
    public String paySuccess(Model model){
        Order order = orderService.findOrderByID(curOrderId);
        order.setPaymentStatus(1);
        orderService.saveOrder(order);
        List<Order> orders =orderService.findOrderByAccount(curAccount);
        List<Hotel> hotels =hotelService.findHotel();
        hotels.clear();
        Hotel hotel;
        for (int i=0;i<orders.size();i++)
        {
            hotel=hotelService.findHotelByID(roomService.findRoomByRoomNumber(orders.get(i).getRoomNumber()).getHotelId());
            hotels.add(hotel);
        }
        model.addAttribute("orders",orders);
        model.addAttribute("hotels",hotels);
        return "/HTML/orderList";
    }
    //退房
    @PostMapping("overOrder")
    public String overOrder(Model model,@RequestParam("orderId") String orderId){

        roomService.findRoomByRoomNumber(orderService.findOrderByID(orderId).getRoomNumber()).setRoomStatus(reRoomStatus);
        //这里改不了
        Order order = orderService.findOrderByID(orderId);
        order.setOrderStatus(2);
        orderService.saveOrder(order);

        System.out.println(orderService.findOrderByID(orderId).getOrderStatus());
//        model.addAttribute("order",orderService.findOrderByID(orderId));

        List<Order> orders =orderService.findOrderByAccount(curAccount);
        List<Hotel> hotels =hotelService.findHotel();
        hotels.clear();
        Hotel hotel;

        for (int i=0;i<orders.size();i++)
        {
            hotel=hotelService.findHotelByID(roomService.findRoomByRoomNumber(orders.get(i).getRoomNumber()).getHotelId());
            hotels.add(hotel);
        }
        model.addAttribute("hotels",hotels);
        model.addAttribute("orders",orders);
        return "/HTML/orderList";
    }

    //支付宝支付接口
    @RequestMapping("/alipayForOrder")
    public void alipayForOrder(HttpServletRequest request, HttpServletResponse response,@RequestParam("orderId") String orderId)
            throws IOException {
        AlipayClient alipayClient = new
                DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                "2016100100639609",
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCrHBYdeYCjyDzSmTi7O92BA696z67my/E0JnXUBWy0/BLQ/FQbR6ESoPpjfEorTos+xtwlZUDDlCbkY/XHtIH6NfR5qBzZYItXgdkHr2kcSlaoqUuQkPIW2fHMIeZyTtgIeJMRcIUVQJsmCefJn8v47uFXreO8ydMVE08KNwMs5WuZtw6eYEKzVx/G8JFIbxgphN/ptXVW7y5w9chkuWzZ8nnikkrpE+nC8XoUERgSBVOjj1sPZaSoUP9nkkVKrw/tzfD2PJUw8VSIuVgp6//DMl7KgdEA8noYWuhOQR6ZOT0A6DopB4TR3GPht7KphJwX9bY5L91DIBXpAKID4n/hAgMBAAECggEAdKziJ5cCMKwJTVFNbd6UW7S3o3aaPKY0Aut2zOwmBAMekYJ9l1xwaNN76PqHWKBmMphG5Pj2AGa1XmcK4PIk7wh7e7k2csNyQGk6JBNoCPJnxPornJg5e3uBdUBoculwRdZx8iJXnPZA1N9MPh/IZiX9YlwgPksgs+5GpyB7+dAV38YDvOq2vbpOyxFCMKK7+u7E6h9sDtW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g80pk4uzvdgQOves+u5svxNCZ11AVstPwS0PxUG0ehEqD6Y3xKK06LPsbcJWVAw5Qm5GP1x7SB+jX0eagc2WCLV4HZB69pHEpWqKlLkJDyFtnxzCHmck7YCHiTEXCFFUCbJgnnyZ/L+O7hV63jvMnTFRNPCjcDLOVrmbcOnmBCs1cfxvCRSG8YKYTf6bV1Vu8ucPXIZLls2fJ54pJK6RPpwvF6FBEYEgVTo49bD2WkqFD/Z5JFSq8P7c3w9jyVMPFUiLlYKev/wzJeyoHRAPJ6GFroTkEemTk9AOg6KQeE0dxj4beyqYScF/W2OS/dQyAV6QCiA+J/4QIDAQAB",
                "RSA2" );
        //订单号
        String out_trade_no = orderId;
        curOrderId =orderId;
        out_trade_no = URLDecoder.decode(out_trade_no,"UTF-8");
        //价格
        String total_amount = orderService.findOrderByID(orderId).getPrice().toString();
        System.out.println(orderService.findOrderByID(orderId).getPrice().toString());
        total_amount = URLDecoder.decode(total_amount,"UTF-8");
        //商品名称
        String subject = orderService.findOrderByID(orderId).getHotelName()+"酒店的"+orderService.findOrderByID(orderId).getRoomType();
        subject = URLDecoder.decode(subject,"UTF-8");
        //商品描述
        String body = "你在支付一个房间哦";
        body = URLDecoder.decode(body,"UTF-8");

        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://192.168.101.2:8080/HTML/paySuccess");
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\""+ out_trade_no +"\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":"+ total_amount +"," +
                "    \"subject\":\""+ subject +"\"," +
                "    \"body\":\""+ body +"\"" +
                "    }"+
                "  }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(form);//直接将完整的表单html输出到页面
        response.getWriter().close();
    }

    //支付宝退钱接口
    @RequestMapping("/alipayRefund")
    public void alipayRefund(HttpServletRequest request, HttpServletResponse response,@RequestParam("orderId") String orderId)
            throws IOException, AlipayApiException {
        curOrderId= orderId;
        AlipayClient alipayClient = new
                DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                "2016100100639609",
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCrHBYdeYCjyDzSmTi7O92BA696z67my/E0JnXUBWy0/BLQ/FQbR6ESoPpjfEorTos+xtwlZUDDlCbkY/XHtIH6NfR5qBzZYItXgdkHr2kcSlaoqUuQkPIW2fHMIeZyTtgIeJMRcIUVQJsmCefJn8v47uFXreO8ydMVE08KNwMs5WuZtw6eYEKzVx/G8JFIbxgphN/ptXVW7y5w9chkuWzZ8nnikkrpE+nC8XoUERgSBVOjj1sPZaSoUP9nkkVKrw/tzfD2PJUw8VSIuVgp6//DMl7KgdEA8noYWuhOQR6ZOT0A6DopB4TR3GPht7KphJwX9bY5L91DIBXpAKID4n/hAgMBAAECggEAdKziJ5cCMKwJTVFNbd6UW7S3o3aaPKY0Aut2zOwmBAMekYJ9l1xwaNN76PqHWKBmMphG5Pj2AGa1XmcK4PIk7wh7e7k2csNyQGk6JBNoCPJnxPornJg5e3uBdUBoculwRdZx8iJXnPZA1N9MPh/IZiX9YlwgPksgs+5GpyB7+dAV38YDvOq2vbpOyxFCMKK7+u7E6h9sDtWgatznI4J8x7+PtJ3Mdisgbk1FZclZHOPc9ZIexv8SgM9ak8q2WLnKrp/0nAELcMTgkD44ZfEpN80Dnb/xKXAgiBz++rF57fmMFPuDfUSXj0VPOTfhTBoW9TekFmFsrPqOHQrKX6WWQQKBgQDyT22WH1lk74LSAIiUcSNMasdFDS5o8eCNJaUZ8k4qmqgntJ/12HkbR7UOJRgJXDY+XX+3MEHsq3aQG1nlqlZ8EGmLU1jN6awc+HBydVrVO1EQRcTxyaH+HdIGAih/0ft7hdgFCTONJCBbul9O0k0cOD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Og6KQeE0dxj4beyqYScF/W2OS/dQyAV6QCiA+J/4QIDAQAB",
                "RSA2" );
        AlipayTradePrecreateRequest rfrequest = new AlipayTradePrecreateRequest();//创建API对应的request类
        String out_trade_no = orderId;
        String total_amount = orderService.findOrderByID(orderId).getPrice().toString();
        System.out.println(orderService.findOrderByID(orderId).getPrice().toString());
        total_amount = URLDecoder.decode(total_amount,"UTF-8");
        String subject = orderService.findOrderByID(orderId).getHotelName()+"酒店的"+orderService.findOrderByID(orderId).getRoomType();
        subject = URLDecoder.decode(subject,"UTF-8");

        rfrequest.setBizContent("{" +
                "    \"out_trade_no\":\""+ out_trade_no +"\"," +
                "    \"total_amount\":"+ total_amount +"," +
                "    \"subject\":\""+ subject +"\"," +
                "    \"store_id\":\"001\"," +
                "    \"timeout_express\":\"90m\"}");//设置业务参数
        AlipayTradePrecreateResponse rfresponse = alipayClient.execute(rfrequest);
        System.out.print(rfresponse.getBody());
        rfrequest.setReturnUrl("http://192.168.101.2:8080/HTML/refundSuccess");
    }
}
